<template>
  <!-- 顶部卡片已经提取为公共组件，通过descInfo传递描述信息 -->
  <header-desc :descInfo=descInfo></header-desc>

  <!-- 中间表单 -->
  <el-card style="height: 350px">
    <el-form ref="formRef" style="max-width: 600px" label-width="auto" label-position="right" size="small"
      :model=myForm>
      <!-- 城市区域下拉框 -->
      <el-form-item label="工单城市" prop="cityId" :rules="[{ required: true, message: '请选择城市', trigger: 'change' }]">
        <el-select v-model.number="myForm.cityId" filterable placeholder="请选择城市" style="width: 200px">
          <el-option v-for="item in myForm.cityList" :key="item.id" :label="item.city_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单区域" prop="areaId" :rules="[{ required: true, message: '请选择区域', trigger: 'change' }]">
        <!-- v-model.number 修饰符会转换输入字符串为数字 -->
        <el-select v-model.number="myForm.areaId" filterable placeholder="请选择区域" style="width: 200px">
          <el-option v-for="item in myForm.areaList" :key="item.id" :label="item.area_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- 手机号数字输入框、模拟生成按钮 -->
      <el-form-item label="车主手机号" prop="phone" :rules="[{ required: true, message: '请输入手机号', trigger: 'change' }]">
        <!-- clearable 输入数据可点击X清除  spellcheck取消语法检测，否则输入内容会有红色下滑波浪线 -->
        <el-input style="width: 200px;" placeholder="请输入手机号" clearable v-model="myForm.phone" spellcheck="false" />
        <span style="padding-left: 15px; "><el-button type="primary" @click="clickPhoneHandler">模拟生成</el-button></span>
      </el-form-item>
      <!-- 日期时间选择框 -->
      <el-form-item label="上牌时间" prop="dateTime">
        <el-date-picker v-model="myForm.dateTime" style="width: 200px" type="datetime" placeholder="请选择日期和时间"
          value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <!-- 工单类型单选按钮 -->
      <el-form-item label="工单类型" prop="orderType">
        <!-- 单选按钮value 需要是字符串，所以不能使用 v-model.number修饰符，否则无法点击 -->
        <el-radio-group v-model="myForm.orderType" class="ml-4">
          <el-radio value="1" size="small">优质工单</el-radio>
          <el-radio value="0" size="small">普通工单</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 备注信息输入框 -->
      <el-form-item label="备注信息" prop="remark">
        <el-input style="width: 200px" :rows="2" type="textarea" placeholder="工单备注信息" clearable spellcheck="false"
          v-model="myForm.remark" />
      </el-form-item>

      <div style="height: 10px;">
        <!-- 占位符，增加按钮与表单的距离 # 我们验证了子传父使用 emit + watch 但点击重置，清空子组件内容未实现，from内暂不做嵌套 -->
      </div>

      <!-- 提交重置按钮 -->
      <el-col :offset=1>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-col>
    </el-form>
  </el-card>

  <!-- 底部结果输出， 通过myResponse传递结果-->
  <bottom-result :myResponse="myResponse"></bottom-result>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import HeaderDesc from '@/components/header/HeaderDesc.vue'
import BottomResult from '@/components/bottom/BottomResult.vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'


// 顶部卡片，描述信息，传递给子组件
const descInfo = reactive({
  title: '构造工单',
  desc: '构造合伙人源线索工单，选择城市区域，输入手机号，选择上牌时间（可选）、工单类型，输入备注信息（可选）即可成单',
  person: 'xpcs',
  remark: '上牌时间不选择，默认为当前时间，备注不输入，默认为空'
})

// ref关联from
const formRef = ref()

// 中间卡片，from表单数据
const myForm = reactive({
  cityList: [],
  areaList: [],
  cityId: '',
  areaId: '',
  phone: '',
  dateTime: '',
  orderType: "1",
  remark: ''
})

// 提交表单，返回数据
const myResponse = reactive({
  code: '',
  msg: '',
  data: ''
})

// 获取城市列表
onMounted(async () => {
  await request.get('/partner/cities').then(res => {
    myForm.cityList = res.data.data
  }).catch(() => {
    ElMessage({
      type: 'error',
      message: '服务内部错误！',
    })
  })
})

// 模拟生成手机号事件
const clickPhoneHandler = async () => {
  await request.get('/partner/phone').then(res => {
    myForm.phone = res.data.data
  }).catch(() => {
    ElMessage({
      // 响应码大于300、请求超时异常、then内部异常走到此分支
      type: 'error',
      message: '服务内部错误！',
    })
  })
}

// from表单提交事件
const submitForm = (formEl) => {
  if (!formEl) return
  // 必填项校验
  formEl.validate(async (valid) => {
    if (valid) {
      // console.log('submit!')
      let data = {
        city_id: myForm.cityId,
        area_id: myForm.areaId,
        phone_number: myForm.phone,
        listen_time: myForm.dateTime,
        order_type: myForm.orderType,
        remark: myForm.remark
      }
      // console.log(data)
      await request.postJson('/partner/order', data).then(res => {
        // console.log(res.data)
        myResponse.code = res.data.code
        myResponse.msg = res.data.msg
        myResponse.data = res.data.data
      }).catch(() => {
        ElMessage({
          type: 'error',
          message: '服务内部错误！',
        })
      })
    }
  })
}

// form表单重置、必填项校验，需要form配置ref和model，表单项配置prop，rule
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

// 侦听cityId发生变化，重新拉取区域列表
// reactive的属性需要使用 () => myFrom.cityId
watch(() => myForm.cityId, async (newValue) => {
  let data = { city_id: newValue }
  await request.get('/partner/areas', data).then(res => {
    // res.data 响应参数
    myForm.areaList = res.data.data
    myForm.areaId = ''
  }).catch(() => {
    ElMessage({
      type: 'error',
      message: '服务内部错误！',
    })
  })
})
</script>
